package com.wending.main_page;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.wending.R;
import com.wending.application.MyApplication;
import com.wending.base_method.NetworkDetector;
import com.wending.bean.User;
import com.wending.config.Constant;
import com.wending.fragment.LoginFragment;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, MyWebViewFragment.BackHandlerInterface, LoginFragment.TunWebViewInterface {

    private ViewPager mViewPager;
    private List<Fragment> mDatas;
    //    private FragmentPagerAdapter mAdapter;
    private MyViewPagerAdapter mAdapter;
    private RadioButton btn0, btn1, btn2, btn3, btn4;
    private Drawable drawable0;
    private Drawable drawable0c;
    private Drawable drawable1;
    private Drawable drawable1c;
    private Drawable drawable2;
    private Drawable drawable2c;
    private Drawable drawable3;
    private Drawable drawable3c;
    private Drawable drawable4;
    private Drawable drawable4c;
    private Drawable drawable1_c, drawable1c_c;
    private boolean isLoginToWoDe = false;
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            getHaveMsg();
        }
    };
    private RadioGroup radiogroup;
        private TimerTask taskLogin = new TimerTask() {
        @Override
        public void run() {
            Log.i("AAAAAA====", "登录timer");
            Login();
        }
    };
    private Button btnmsg;
    private BadgeView badgeView;

    private void Login() {
        List<User> all = DataSupport.findAll(User.class);
        if (all != null && all.size() > 0 && all.get(0) != null) {
            User user = all.get(0);
            String url = Constant.Login + "?password=" + user.getPassword() + "&username=" + user.getUsername();
            StringRequest loginRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            }) {
                //重写parseNetworkResponse方法，返回的数据中 Set-Cookie:***************;
                //其中**************为session id
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
//                return super.parseNetworkResponse(response);
                    Response<String> superResponse = super
                            .parseNetworkResponse(response);
                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    //Constant是一个自建的类，存储常用的全局变量
                    Constant.localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                    Log.d("MMMM", "sessionid-------------====" + Constant.localCookie);
                    MyWebViewFragment wode = new MyWebViewFragment();
                    Bundle bb = new Bundle();
                    bb.putString("data", Constant.woDe);
                    wode.setArguments(bb);
                    mDatas.add(wode);
                    mAdapter.notifyDataSetChanged();
                    return superResponse;
                }
            };
            MyApplication.requestQueue.add(loginRequest);
            MyApplication.requestQueue.start();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFragment();
        initRadioButton();
        btn0.setChecked(true);
        mViewPager.setCurrentItem(0);
        setRadioButton(0);
        checkNetWork();
        Timer timer = new Timer(true);
        timer.schedule(task, 0, 10000);

//        Timer timerLogin=new Timer(true);
//        timerLogin.schedule(taskLogin,0,8*1000);
    }

    private void initRadioButton() {

        badgeView = BadgeFactory.create(this)
                .setWidthAndHeight(8, 8)
                .setBadgeBackground(Color.RED)
                .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                .setBadgeCount(80)
                .setShape(BadgeView.SHAPE_CIRCLE);
        btnmsg = (Button) findViewById(R.id.btnmsg);
        radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
        btn0 = (RadioButton) findViewById(R.id.btn0);
        btn1 = (RadioButton) findViewById(R.id.btn1);
        btn2 = (RadioButton) findViewById(R.id.btn2);
        btn3 = (RadioButton) findViewById(R.id.btn3);
        btn4 = (RadioButton) findViewById(R.id.btn4);
        radiogroup.setOnCheckedChangeListener(this);

        drawable0 = getResources().getDrawable(R.drawable.icon_shouye_g);
        drawable0c = getResources().getDrawable(R.drawable.icon_shouye_o);
        drawable1 = getResources().getDrawable(R.drawable.icon_liaotian_g);
        drawable1c = getResources().getDrawable(R.drawable.icon_liaotian_o);
        drawable2 = getResources().getDrawable(R.drawable.icon_shequ_g);
        drawable2c = getResources().getDrawable(R.drawable.icon_shequ_o);
        drawable3 = getResources().getDrawable(R.drawable.icon_dongtai_g);
        drawable3c = getResources().getDrawable(R.drawable.icon_dongtai_o);
        drawable4 = getResources().getDrawable(R.drawable.icon_wode_g);
        drawable4c = getResources().getDrawable(R.drawable.icon_wode_o);

        drawable1_c = getResources().getDrawable(R.drawable.icon_liaotian_g_c);
        drawable1c_c = getResources().getDrawable(R.drawable.icon_liaotian_o_c);

        //获取屏幕分辨率并显示出来
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int iconW = dm.widthPixels;
        int iconH = dm.heightPixels;
        int winth = px2dip(this, iconW);
        int rbWH = iconW / 18;//获得屏幕宽度
        drawable0.setBounds(0, 0, rbWH, rbWH);
        drawable0c.setBounds(0, 0, rbWH, rbWH);
        drawable1.setBounds(0, 0, rbWH, rbWH);
        drawable1.setBounds(0, 0, rbWH, rbWH);
        drawable1c.setBounds(0, 0, rbWH, rbWH);
        drawable2.setBounds(0, 0, rbWH, rbWH);
        drawable2c.setBounds(0, 0, rbWH, rbWH);
        drawable3.setBounds(0, 0, rbWH, rbWH);
        drawable3c.setBounds(0, 0, rbWH, rbWH);
        drawable4.setBounds(0, 0, rbWH, rbWH);
        drawable4c.setBounds(0, 0, rbWH, rbWH);
        drawable1_c.setBounds(0, 0, rbWH, rbWH);
        drawable1c_c.setBounds(0, 0, rbWH, rbWH);
    }

    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private void initFragment() {
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.setOffscreenPageLimit(5);

        //添加5个页面
        mDatas = new ArrayList<>();
        MyWebViewFragment fr0 = new MyWebViewFragment();
        MyWebViewFragment fr1 = new MyWebViewFragment();
        MyWebViewFragment fr2 = new MyWebViewFragment();
        MyWebViewFragment fr3 = new MyWebViewFragment();

        Bundle bundle0 = new Bundle();
        bundle0.putString("data", Constant.zhuYe);
        fr0.setArguments(bundle0);
        Bundle bundle1 = new Bundle();
        bundle1.putString("data", Constant.liaoTian);
        fr1.setArguments(bundle1);
        Bundle bundle2 = new Bundle();
        bundle2.putString("data", Constant.sheQu);
        fr2.setArguments(bundle2);
        Bundle bundle3 = new Bundle();
        bundle3.putString("data", Constant.dongTai);
        fr3.setArguments(bundle3);

        mDatas.add(fr0);
        mDatas.add(fr1);
        mDatas.add(fr2);
        mDatas.add(fr3);
        Log.i("CCCooke====", TextUtils.isEmpty(Constant.localCookie) + "");
//        LoginFragment fr4 = new LoginFragment();
//        mDatas.add(fr4);
        if (DataSupport.findFirst(User.class)!=null) {
            MyWebViewFragment wode = new MyWebViewFragment();
            Bundle bb = new Bundle();
            bb.putString("data", Constant.woDe);
            wode.setArguments(bb);
            mDatas.add(wode);
        }else {
//            if (DataSupport.findFirst(User.class)!=null){
//                Login();
//            }else {
                LoginFragment fr4 = new LoginFragment();
                mDatas.add(fr4);
//            }
        }
        //Fragment适配器
//        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
//            @Override
//            public int getCount() {
//                return mDatas.size();
//            }
//
//            @Override
//            public Fragment getItem(int arg0) {
//                return mDatas.get(arg0);
//            }
//        };
        mAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), mDatas);
        mViewPager.setAdapter(mAdapter);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.btn0:
                mViewPager.setCurrentItem(0);
                setRadioButton(0);
                break;
            case R.id.btn1:
                mViewPager.setCurrentItem(1);
                setRadioButton(1);
                break;
            case R.id.btn2:
                mViewPager.setCurrentItem(2);
                setRadioButton(2);
                break;
            case R.id.btn3:
                mViewPager.setCurrentItem(3);
                setRadioButton(3);
                break;
            case R.id.btn4:
                mViewPager.setCurrentItem(4);
                setRadioButton(4);
                break;
        }
    }

    //检查网络
    protected boolean checkNetWork() {
        boolean networkState = NetworkDetector.detect(MainActivity.this);
        if (!networkState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    MainActivity.this);
            builder.setMessage("网络不可用，是否现在设置网络？");
            builder.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivityForResult(new Intent(
                                    Settings.ACTION_WIRELESS_SETTINGS), 0);
                        }
                    });
            builder.setNegativeButton("取消", null);
            builder.show();
        }
        return networkState;
    }

    /**
     * 设置底部按钮
     */
    private void setRadioButton(int vp) {
        switch (vp) {
            case 0:
                btn0.setCompoundDrawables(null, drawable0c, null, null);
                btn1.setCompoundDrawables(null, drawable1, null, null);
                btn2.setCompoundDrawables(null, drawable2, null, null);
                btn3.setCompoundDrawables(null, drawable3, null, null);
                btn4.setCompoundDrawables(null, drawable4, null, null);
                break;
            case 1:
                btn0.setCompoundDrawables(null, drawable0, null, null);
                btn1.setCompoundDrawables(null, drawable1c, null, null);
                btn2.setCompoundDrawables(null, drawable2, null, null);
                btn3.setCompoundDrawables(null, drawable3, null, null);
                btn4.setCompoundDrawables(null, drawable4, null, null);
                break;
            case 2:
                btn0.setCompoundDrawables(null, drawable0, null, null);
                btn1.setCompoundDrawables(null, drawable1, null, null);
                btn2.setCompoundDrawables(null, drawable2c, null, null);
                btn3.setCompoundDrawables(null, drawable3, null, null);
                btn4.setCompoundDrawables(null, drawable4, null, null);
                break;
            case 3:
                btn0.setCompoundDrawables(null, drawable0, null, null);
                btn1.setCompoundDrawables(null, drawable1, null, null);
                btn2.setCompoundDrawables(null, drawable2, null, null);
                btn3.setCompoundDrawables(null, drawable3c, null, null);
                btn4.setCompoundDrawables(null, drawable4, null, null);
                break;
            case 4:
                btn0.setCompoundDrawables(null, drawable0, null, null);
                btn1.setCompoundDrawables(null, drawable1, null, null);
                btn2.setCompoundDrawables(null, drawable2, null, null);
                btn3.setCompoundDrawables(null, drawable3, null, null);
                btn4.setCompoundDrawables(null, drawable4c, null, null);
                break;
        }

        if (isHaveMsg) {
            badgeView.bind(btnmsg);
        } else {
            badgeView.unbind();
        }
    }

    private MyWebViewFragment selectedFragment;

    @Override
    public void setSelectedFragment(MyWebViewFragment backHandledFragment) {
        selectedFragment = backHandledFragment;
    }

    @Override
    public void webViewTunFragment(int position) {
        switch (position) {
            case -2:
                getHaveMsg();
                break;
            case -1://退出
                DataSupport.deleteAll(User.class);
                finish();
                System.exit(0);
                break;
            case 1:
                //登录
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction fTransaction = fm.beginTransaction();
                //删除相应的缓存碎片。
                fTransaction.remove(mDatas.get(4));
                fTransaction.commit();
                mDatas.remove(4);
                LoginFragment fr4 = new LoginFragment();
                mDatas.add(fr4);
                mAdapter.setData(mDatas);
                mAdapter.notifyDataSetChanged();
                btn4.setChecked(true);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Log.w("MainActivity===",
                "onBackPressed" +
                        (selectedFragment == null) + "------" +
                        (selectedFragment != null ? selectedFragment.dispose : "null"));
        if (selectedFragment == null || !selectedFragment.dispose) {
            Log.i("mainonback===", "");
            finish();
            super.onBackPressed();
        }

    }

    @Override
    public void IsToWoDe(boolean b) {
        isLoginToWoDe = b;
        Log.i("b===", b + "");
        if (b) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction fTransaction = fm.beginTransaction();
            //删除相应的缓存碎片。
            fTransaction.remove(mDatas.get(4));
            fTransaction.commit();
            mDatas.remove(4);
            Log.i("mDatas===", mDatas.size() + "");
            MyWebViewFragment wode = new MyWebViewFragment();
            Bundle bundle0 = new Bundle();
            bundle0.putString("data", Constant.woDe);
//            bundle0.putString("data", "https://www.baidu.com/");
            wode.setArguments(bundle0);
            mDatas.add(wode);
            mAdapter.setData(mDatas);
            mViewPager.setCurrentItem(0);
            mAdapter.notifyDataSetChanged();
            btn0.setChecked(true);
            mViewPager.setCurrentItem(0);
            Timer timerLogin=new Timer(true);
            timerLogin.schedule(taskLogin,0,15*60*1000);
        }
    }

    @Override
    public void TurnWhere(int positon) {
        switch (positon) {
            case -1:
                //注册
                FragmentManager fm1 = getSupportFragmentManager();
                FragmentTransaction fTransaction1 = fm1.beginTransaction();
                //删除相应的缓存碎片。
                fTransaction1.remove(mDatas.get(4));
                fTransaction1.commit();
                mDatas.remove(4);
                Log.i("mDatas===", mDatas.size() + "");
                MyWebViewFragment wode1 = new MyWebViewFragment();
                Bundle bundle01 = new Bundle();
                bundle01.putString("data", Constant.ZhuCe);
                bundle01.putInt("registe", 1);
                wode1.setArguments(bundle01);
                mDatas.add(wode1);
                mAdapter.setData(mDatas);
                mAdapter.notifyDataSetChanged();
                switch (mViewPager.getCurrentItem()) {
                    case 0:
                        btn0.setChecked(true);
                        break;
                    case 1:
                        btn1.setChecked(true);
                        break;
                    case 2:
                        btn2.setChecked(true);
                        break;
                    case 3:
                        btn3.setChecked(true);
                        break;
                    case 4:
                        btn4.setChecked(true);
                        break;
                }
                break;
            case 1:
                //注册
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction fTransaction = fm.beginTransaction();
                //删除相应的缓存碎片。
                fTransaction.remove(mDatas.get(4));
                fTransaction.commit();
                mDatas.remove(4);
                Log.i("mDatas===", mDatas.size() + "");
                MyWebViewFragment wode = new MyWebViewFragment();
                Bundle bundle0 = new Bundle();
                bundle0.putString("data", Constant.ZhuCe);
                bundle0.putInt("registe", 1);
                wode.setArguments(bundle0);
                mDatas.add(wode);
                mAdapter.setData(mDatas);
//                mViewPager.setCurrentItem(4);
                mAdapter.notifyDataSetChanged();
//                mViewPager.setCurrentItem(4);
                btn4.setChecked(true);
//                setRadioButton(4);
                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();//将原任务从队列中移除
        }
    }

    boolean isHaveMsg = false;
    int tempMsg = 1;

    //返回结果是0或者1，0说明有未读消息，1没有未读消息，如果有未读消息在聊天上加个小红点。
    public void getHaveMsg() {
        tempMsg++;
        List<User> all = DataSupport.findAll(User.class);
        if (all != null && all.size() > 0 && all.get(0) != null) {
            User user = all.get(0);
            StringRequest request = new StringRequest(Request.Method.GET,
                    Constant.XiaoXiShuLiang
                            + "?msgstate=wd"
                            + "&password=" + user.getUsername()
                            + "&userid=" + user.getUserid()
                    , new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    int currentItem = mViewPager.getCurrentItem();
                    Log.i("MMMMMsgResponse===", response + "");
//                    if (tempMsg % 2 == 0) {
//                        isHaveMsg = true;
////                        //有消息
////                        if (currentItem == 1) {
////                            btn1.setCompoundDrawables(null, drawable1c_c, null, null);
////                        } else {
////                            btn1.setCompoundDrawables(null, drawable1_c, null, null);
////                        }
//                    } else {
//                        isHaveMsg = false;
//
////                        if (currentItem == 1) {
////                            btn1.setCompoundDrawables(null, drawable1c, null, null);
////                        } else {
////                            btn1.setCompoundDrawables(null, drawable1, null, null);
////                        }
//                    }
//                    setRadioButton(currentItem);
                    try {
                        JSONObject object = new JSONObject(response);
                        String msg = (String) object.get("msg");
                        if (msg.equals("0")) {
                            isHaveMsg = true;
                        } else {
                            isHaveMsg = false;
                        }
                        setRadioButton(currentItem);
                    } catch (JSONException e) {
                        Log.w("Cache===",e.toString());
                        isHaveMsg = false;
                        setRadioButton(currentItem);
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            });
            MyApplication.requestQueue.add(request);
            MyApplication.requestQueue.start();
        }
    }
}
